package net.bat.rest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import net.bat.dao.QueryResult;
import net.bat.dao.UserDAO;
import net.bat.dto.ResultDTO;
import net.bat.entity.IdEntity;
import net.bat.filter.ExtReq;
import net.bat.filter.JPAReq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RestService {
	@Autowired
	private UserDAO dao;

	private ExtReq parser;

	@PostConstruct
	public void init() {
		parser = new ExtReq();
	}

	public boolean exists(String entity_name, String pn, Object pv) throws ClassNotFoundException {
		return dao.isExistedByWhere(UserDAO.classForName(entity_name), pn + "=?", new Object[] { pv });
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ResultDTO disticnt(String entity_name, String property_name, String kw, Integer limit, String flt)
			throws Exception {
		ResultDTO<Object> dto = new ResultDTO<Object>();
		Class entity = UserDAO.classForName(entity_name);
		String filter = null;
		if ((kw != null) && !kw.trim().equals("")) {
			if (flt == null) {
				filter = "[{\"property\":\"" + property_name + "\",\"operator\":\"like\",\"value\":\"" + kw + "\"}]";
			} else {
				filter = flt.replace(']', ',') + "{\"property\":\"" + property_name
						+ "\",\"operator\":\"like\",\"value\":\"" + kw + "\"}]";
			}
		}
		JPAReq req = parser.parse(filter, null, entity);

		List<Object> ls = dao.getDistinctByWhere(entity, property_name, limit, req.getWhereql(), req.getQueryParams());
		dto.total = ls.size();
		List data = new ArrayList();
		for (int i = 0; i < dto.total; i++) {
			Object cur = ls.get(i);
			data.add(new Object[] { cur, cur });
		}
		dto.data = data;
		return dto;
	}

	public <T extends IdEntity> T getEntity(String entity_name, Long entityId) throws ClassNotFoundException {
		T r = (T) dao.find(UserDAO.classForName(entity_name), entityId);
		return r;
	}

	public <T extends IdEntity> ResultDTO<?> getEntities(int page, int start, int limit, String filter, String sort,
			String entity_name) throws Exception {
		ResultDTO<T> dto = new ResultDTO<T>();
		Class<T> cls = UserDAO.classForName(entity_name);
		JPAReq req = parser.parse(filter, sort, cls);

		QueryResult<T> result = dao.getScrollData(cls, start, limit, req.getWhereql(), req.getQueryParams(),
				req.getOrderby());
		dto.data = result.getResultlist();
		dto.total = result.getTotalrecord();
		return dto;
	}

	public <T extends IdEntity> T updateEntity(String entity_name, Long id, Map<String, Object> rmap) throws Exception {
		return dao.update(entity_name, id, rmap);
	}

	public <T extends IdEntity> T updateEntity(String entity_name, Map<String, Object> rmap) throws Exception {
		Long id;
		try {
			id = Long.parseLong(rmap.get("id").toString());
		} catch (Exception e) {
			id = null;
		}
		if (id == null) {
			return addEntity(entity_name, rmap);
		} else {
			return dao.update(entity_name, id, rmap);
		}
	}

	public <T extends IdEntity> T addEntity(String entity_name, Map<String, Object> rmap) throws Exception {
		return dao.add(entity_name, rmap);
	}

	public <T extends IdEntity> T removeEntitys(String entity_name, Object[] ids) throws Exception {
		dao.remove(entity_name, ids);
		return null;
	}

}
